import re

import wtforms
from wtforms.validators import Email, DataRequired, Length, ValidationError, EqualTo, InputRequired

from exts import db
from models import UserModel,EmailCode

class RegisterForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message='邮箱不正确')])
    captcha = wtforms.StringField(validators=[Length(min=6, max=6,message='验证码应为6位')])
    username = wtforms.StringField(validators=[Length(min=3,max=20,message='用户名应在3-20位之间')])
    password = wtforms.StringField(validators=[Length(min=8,max=20,message='密码长度应在8-20位之间')])
    password_again=wtforms.StringField(validators=[EqualTo('password',message='两次密码不一致')])

    def validate_email(self,field):
        email = field.data
        user = UserModel.query.filter_by(email=email).first()
        if user:
            raise ValidationError('该用户已被注册！')

    def validate_password(self, field):
        password = field.data
        # 检查是否包含至少1个大写字母
        if not re.search(r'[A-Z]', password):
            raise ValidationError("密码必须包含至少1个大写字母")
        # 检查是否包含至少1个小写字母
        if not re.search(r'[a-z]', password):
            raise ValidationError("密码必须包含至少1个小写字母")
        # 检查是否包含至少1个数字
        if not re.search(r'[0-9]', password):
            raise ValidationError("密码必须包含至少1个数字")

    def validate_captcha(self, field):
        code = field.data
        email=self.email.data
        email_code = EmailCode.query.filter_by(code=code,email=email).first()
        if not email_code:
            raise ValidationError('邮箱或验证码错误')
        else:
            db.session.delete(email_code)
            db.session.commit()

class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message='邮箱不正确')])
    password = wtforms.StringField(validators=[Length(min=8, max=20, message='密码长度应在8-20位之间')])

class QuestionForm(wtforms.Form):
    title = wtforms.StringField(validators=[Length(min=3,max=200,message='标题需长度需在3-200字之间')])
    content = wtforms.StringField(validators=[Length(min=3,message='内容需大于3个字')])

class AnswerForm(wtforms.Form):
    content=wtforms.StringField(validators=[Length(min=3,message='内容需大于3个字')])
    question_id=wtforms.IntegerField(validators=[InputRequired(message='必须传入问题id')])

